<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button type="text" size="small" icon="el-icon-view" @click.stop="handleView(row)">详情</el-button>
      </template>
    </avue-crud>
    <el-dialog v-dragDirectives append-to-body :close-on-click-modal="false" title="详情" :visible.sync="showDialog" v-if="showDialog" width="60%" top="7vh">
      <div class="title-result">
        <div class="title">
          <i class="el-icon-vertical-bar avue-group__icon"></i>
          <h3>采购单信息</h3>
        </div>
      </div>
      <avue-form ref="properties" v-model="properties" :option="propertiesOption"></avue-form>
      <div class="title-result">
        <div class="title">
          <i class="el-icon-vertical-bar avue-group__icon"></i>
          <h3>物料详情</h3>
        </div>
      </div>
      <avue-crud
        :option="sheetOption"
        @current-change="currentDetailChange"
        @size-change="sizeDetailChange"
        :page.sync="detailPage"
        :table-loading="detailLoading"
        :data="sheetData"
        ref="addTableCrud"
      >
      </avue-crud>
      <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, getDetailList } from '@/api/warehouse/purchase-order-manage';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userConfig from '@/mixins/userConfig';
import userTableConfig from '@/components/user-table-config/index.vue';

export default {
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'PURCHASE_ORDER_MANAGE',
      form: {},
      sheetForm: {},
      properties: {},
      timer: new Date().getTime(),
      loading: false,
      detailLoading: false,
      isNone: '', //是否显示修改
      title: '',
      status: '',
      tableOption: [], //模态框配置
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      rowData: {}, //行数据
      selectionList: [],
      selectionDetailList: [],
      showDialog: false,
      data: [],
      sheetData: [],
      option: {
        calcHeight: 30,
        tip: false,
        dialogClickModal: false,
        border: true,
        height: 'calc(100vh - 440px)',
        viewBtn: false,
        addBtn: false,
        selection: false,
        printBtn: false,
        editBtn: false,
        delBtn: false,
        index: true,
        indexLabel: '序号',
        menu: true,
        menuWidth: 150,
        searchSpan: 5,
        searchShow: true,
        searchMenuPosition: 'right',
        searchMenuSpan: 12,
        searchLabelWidth: 100,
        columnBtn: false,
        column: [
          {
            label: '采购单号',
            prop: 'purchaseOrderNo',
            width: 180,
            search: true,
            searchSpan: 6,
            searchOrder: 1,
            rules: [
              {
                required: true,
                message: '请输入采购单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '供应商',
            prop: 'vendorName',
            search: true,
            searchSpan: 6,
            searchOrder: 2,
            rules: [
              {
                required: true,
                message: '请输入供应商',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '预定到达时间',
            prop: 'reservationArrivalTime',
            search: true,
            searchSpan: 6,
            searchOrder: 5,
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
          },
          {
            label: '单据状态',
            prop: 'status',
            search: true,
            searchSpan: 6,
            searchOrder: 6,
            type: 'select',
            dataType: 'string',
            dicData: [
              { label: '正常', value: '1' },
              { label: '完成', value: '2' },
              { label: '取消', value: '3' },
              { label: '关闭', value: '4' }
            ]
          },
          {
            label: '来源',
            prop: 'sourceType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=sheet_source',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          }
        ]
      },
      propertiesOption: {
        //单据FORM配置
        labelWidth: '110',
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '采购单号',
            prop: 'purchaseOrderNo',
            disabled: true,
            span: 7
          },
          {
            label: '供应商',
            prop: 'vendorName',
            type: 'search',
            disabled: true,
            span: 7
          },
          {
            label: '单据状态',
            prop: 'status',
            type: 'select',
            disabled: false,
            display: true,
            disabled: true,
            dataType: 'string',
            span: 7,
            dicData: [
              { label: '正常', value: '1' },
              { label: '完成', value: '2' },
              { label: '取消', value: '3' },
              { label: '关闭', value: '4' }
            ]
          }
        ]
      },
      sheetOption: {
        tip: false,
        searchShow: true,
        searchSpan: 4,
        searchMenuSpan: 6,
        dialogClickModal: false,
        height: '400',
        columnBtn: false,
        border: true,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        cancelBtn: false,
        saveBtn: false,
        selection: false,
        menu: false,
        page: true,
        index: true,
        indexLabel: '序号',
        refreshBtn: false,
        expandBtn: false,
        column: [
          {
            label: '行号',
            prop: 'purchaseOrderLot'
          },
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料品牌',
            prop: 'partBrand'
          },
          {
            label: '物料规格',
            prop: 'partSpec'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '采购数量',
            prop: 'quantity'
          },
          {
            label: '单位',
            prop: 'uom'
          },
          {
            label: '已入库数量',
            prop: 'storageQuantity'
          },
          {
            label: '待入库数量',
            prop: 'preStorageQuantity'
          },
          {
            label: '收料数量',
            prop: 'receivingQuantity'
          },
          {
            label: '可收数量',
            prop: 'openQuantity'
          }
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.purchaseOrderManage_add, false),
        viewBtn: this.vaildData(this.permission.purchaseOrderManage_view, false),
        delBtn: this.vaildData(this.permission.purchaseOrderManage_delete, false),
        editBtn: this.vaildData(this.permission.purchaseOrderManage_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    handleView(row) {
      this.properties = {};
      this.sheetData = [];
      this.properties = row;
      getDetailList(this.detailPage.currentPage, this.detailPage.pageSize, { purchaseOrderNo: row.purchaseOrderNo }).then((res) => {
        let data = res.data.data;
        this.detailPage.total = data.total;
        this.sheetData = data.records || [];
      });
      this.showDialog = true;
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete(titleCrud) {
      if (titleCrud == 'sheetDel') {
        if (this.selectionList.length === 0) {
          this.$message.warning('请选择至少一条数据');
          return;
        }
        this.$confirm('确定将选择数据删除?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.$refs.crud.toggleSelection();
          });
      }
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.reservationArrivalTime && params.reservationArrivalTime.length > 1) {
        params.startTime = params.reservationArrivalTime[0];
        params.endTime = params.reservationArrivalTime[1];
        delete params.reservationArrivalTime;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionDetailChange(list) {
      this.selectionDetailList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentDetailChange(currentPage) {
      this.detailPage.currentPage = currentPage;
      this.handleView(this.properties);
    },
    sizeDetailChange(pageSize) {
      this.detailPage.pageSize = pageSize;
      this.handleView(this.properties);
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    reset() {
      this.showDialog = false;
    },
    handleDetailDelete() {
      if (this.selectionDetailList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.sheetData = this._differenceBy(this.sheetData, this.selectionDetailList, 'partMasterCode');
    },
    ransferToNumber(inputNumber) {
      if (isNaN(inputNumber) || !inputNumber) {
        return inputNumber;
      }
      inputNumber = '' + inputNumber;
      inputNumber = parseFloat(inputNumber);
      let eformat = inputNumber.toExponential(); // 转换为标准的科学计数法形式（字符串）
      let tmpArray = eformat.match(/\d(?:\.(\d*))?e([+-]\d+)/); // 分离出小数值和指数值
      let number = inputNumber.toFixed(Math.max(0, (tmpArray[1] || '').length - tmpArray[2]));
      return number;
    },
    /*
     * 提交
     */
    submit() {
      const that = this;
      that.$refs.properties.validate((valid, done) => {
        if (!valid) return;
        that.$refs.addTableCrud.validateCellForm().then((res) => {
          let obj = res || {};
          if (Object.keys(obj).length === 0) {
            if (that.judgeSheetLotRepeat(that.sheetData)) {
              that.$message.warning('采购单行号重复，请检查并修改!');
              return;
            }
            if (that.sheetData.length == 0) {
              that.$message.warning('单据明细不能为空，请检查！');
              return;
            }
            let sheetDetails = that.sheetData.map((item) => {
              return {
                id: item.id,
                generationType: item.generationType,
                purchaseOrderNo: that.properties.purchaseOrderNo,
                reservationArrivalTime: that.properties.reservationArrivalTime,
                status: that.properties.status,
                vendorCode: that.properties.vendorCode,
                vendorId: that.properties.vendorId,
                vendorName: that.properties.vendorName,
                purchaseOrderLot: item.purchaseOrderLot,
                partName: item.partName,
                partNo: item.partNo,
                partModel: item.partModel,
                partMasterId: item.partMasterId,
                partType: item.partType,
                quantity: item.quantity,
                uom: item.uom
              };
            });
            console.log(this.sheetData, 'this.sheetData');
            console.log(sheetDetails, sheetDetails);
            add(sheetDetails).then(
              (res) => {
                this.$message.success(`${this.title === '新增' ? '创建' : '编辑'}成功!`);
                done();
                this.showDialog = false;
                this.resetForm();
                this.refreshChange();
              },
              (error) => {
                done();
                console.log(error);
              }
            );
          }
        });
      });
    },
    /**
     * 选择模态框数据
     */
    async getSelectedRows(rowData, titleInfo) {
      const that = this;
      switch (titleInfo) {
        //  添加供应商信息
        case 'vendorName':
          that.$set(that.properties, 'vendorName', rowData.name);
          that.$set(that.properties, 'vendorCode', rowData.partnerNo);
          that.$set(that.properties, 'vendorId', rowData.id);
          break;
        // 添加物料信息
        case 'partInfo':
          let flag = that.isRepeatPart(that.sheetData, rowData, 'partNo');
          if (!flag) return;
          let result = rowData.map((item) => {
            return {
              partNo: item.partNo,
              partName: item.name,
              partModel: item.partModel,
              partMasterId: item.id,
              partType: item.partType,
              uom: item.uom,
              purchaseOrderLot: item.purchaseOrderLot,
              purchaseOrderNo: item.purchaseOrderNo,
              quantity: item.quantity,
              vendorName: item.vendorName,
              vendorCode: item.vendorCode,
              vendorId: item.vendorId,
              status: item.status,
              reservationArrivalTime: item.reservationArrivalTime,
              $cellEdit: true
            };
          });
          result = result.concat(that.sheetData);
          that.sheetData = result;
          // that.sheetData = that._orderBy(result, ['purchaseOrderLot'], ['asc']);
          break;
        default:
          break;
      }
    },
    /**
     * 判断物料数据是否有相同
     */
    isRepeatPart(arr1, arr2, attr1) {
      let flag = this._some(arr1, (item1) => {
        return this._some(arr2, (item2) => {
          return item1[attr1] === item2[attr1];
        });
      });
      if (flag) {
        this.$message({
          type: 'warning',
          message: '选择的物料与已选的物料有重复,请重新选择'
        });
        return false;
      }
      return true;
    },
    //数据重置
    resetForm() {
      this.$nextTick(() => {
        this.$refs.properties.resetForm();
      });
      this.properties = {};
      this.sheetData = [];
    },
    //判断单行号是否重复
    judgeSheetLotRepeat(data) {
      let len = data.length;
      for (let i = 0; i < len; i++) {
        for (let j = i + 1; j < len; j++) {
          if (data[i].purchaseOrderLot == data[j].purchaseOrderLot) {
            return true;
          }
        }
      }
      return false;
    },
    /**
     * 供应商信息模态框
     */
    openPartnerModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择供应商信息（双击进行选择）',
        url: '/api/mes-admin/vendor/page',
        isPage: true,
        index: false,
        rowSelectionType: 'single',
        titleInfo: 'vendorName',
        columnDefs: [
          // },
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '缩写',
            prop: 'abbreviation'
          },
          {
            label: '联系人',
            prop: 'principal'
          },
          {
            label: '联系方式',
            prop: 'contacts'
          },
          {
            label: '位置',
            prop: 'locations'
          }
        ]
      };
    },
    /**
     * 打开物料信息模态框
     */
    openPartModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择物料信息',
        url: '/api/mes-admin/part-master/page?partType=MATERIAL',
        index: false,
        isPage: true,
        rowSelectionType: '',
        titleInfo: 'partInfo',
        columnDefs: [
          {
            label: '物料类型',
            prop: 'categoryId',
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          },
          {
            label: '物料型号',
            prop: 'partModel'
          }
        ]
      };
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    column(prop) {
      return this.findObject(this.sheetOption.column, prop);
    },
    formColumn(prop) {
      return this.findObject(this.propertiesOption.column, prop);
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .avue-form__group .avue-form__menu.avue-form__menu--center {
  display: none;
}
.title-result {
  display: flex;
  justify-content: space-between;
  .title {
    display: flex;
    align-items: center;
  }
}

::v-deep .el-dialog .el-card__body {
  .avue-crud__menu {
    display: none;
  }
}
</style>
